<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("paymentList", $this->model->getPaymentList());
        $this->view->assign("priceTypeList", $this->model->getPriceTypeList());
    }
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $where2 = [];
            if(!in_array(1,array_column($this->auth->getGroups(),'group_id'))){
                $courseIds = Db::name('course')->alias('c')
                    ->join('teacher t','c.teacher_id = t.id')
                    ->where('t.admin_id',$this->auth->id)
                    ->field('c.id')
                    ->select();
                $where2['courseId'] = ['in',array_column($courseIds,"id")];
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['cashflow','student','course'])
                    ->where($where)->where($where2)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['cashflow','student','course'])
                    ->where($where)->where($where2)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','sn','userId','phone','batch_id','status','title','courseId','amount','total_price','discountId','discount','refundId','coupon','payment','coin_amount','coin_rate','price_type','paid_time','cash_sn','note','data','refund_end_time','create_time']);
                $row->visible(['cashflow']);
				$row->getRelation('cashflow')->visible(['amount']);
				$row->visible(['student']);
				$row->getRelation('student')->visible(['nick_name','phone']);
				$row->visible(['course']);
				$row->getRelation('course')->visible(['title']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
}
